<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { Delete, Plus } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import request from '@/utils/request'

interface User {
  id: number
  username: string
  email: string
  createdAt: string
  roles: string[]
}

interface UserListResponse {
  current: number
  total: number
  pages: number
  size: number
  records: User[]
}

interface UserModel {
  username: string
  password: string
  email: string
  roleIds: number[]
}

interface RoleOption {
  id: number
  name: string
}

// 角色选项数据
const roleOptions: RoleOption[] = [
  { id: 1, name: '采购员' },
  { id: 2, name: '设备管理员' },
  { id: 3, name: '科室人员' },
  { id: 4, name: '财务人员' },
  { id: 5, name: '日志监管员' },
  { id: 6, name: '超级管理员' }
]

const userApi = {
  getUserList: (params: any) => request<UserListResponse>({
    method: 'POST',
    url: '/admin/user/list',
    data: params
  }),
  addUser: (data: UserModel) => request<string>({
    method: 'POST',
    url: '/admin/user/add',
    data
  }),
  deleteUser: (id: number) => request<string>({
    method: 'DELETE',
    url: `/admin/user/${id}`
  })
}

const userList = ref<User[]>([])
const formModel = ref<UserModel>({
  username: '',
  password: '',
  email: '',
  roleIds: []
})

const isSubmitting = ref(false)
const loading = ref(false)

// const titleName = '用户管理系统'
const title = ref('添加用户')
const visibleDrawer = ref(false)

const searchMessage = ref({
  username: '',
  roleName: '' // 改为单选框，字段名与后端一致
})

const pageNum = ref(1)
const pageSize = ref(7)
const total = ref(0)

onMounted(() => {
  getDataListWithCondition()
})

const getDataListWithCondition = async () => {
  loading.value = true
  try {
    const params: any = {
      page: pageNum.value,
      size: pageSize.value,
      username: searchMessage.value.username,
      roleName: searchMessage.value.roleName // 使用 roleName 而非 roleNames
    }

    const res = await userApi.getUserList(params)
    userList.value = res.data.records.map(user => ({
      ...user,
      createdAt: formatDateTime(user.createdAt)
    }))
    total.value = res.data.total
  } catch (error) {
    ElMessage.error('获取用户列表失败')
  } finally {
    loading.value = false
  }
}

const formatDateTime = (dateTime: string) => {
  if (!dateTime) return ''
  const date = new Date(dateTime)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  }).replace(/\//g, '-')
}

const validateForm = () => {
  if (!formModel.value.username) {
    ElMessage.warning('请输入用户名')
    return false
  }
  if (!formModel.value.password) {
    ElMessage.warning('请输入密码')
    return false
  }
  if (!formModel.value.email) {
    ElMessage.warning('请输入邮箱')
    return false
  }
  if (formModel.value.roleIds.length === 0) {
    ElMessage.warning('请至少选择一个角色')
    return false
  }
  return true
}

const handleSubmit = async () => {
  if (isSubmitting.value || !validateForm()) return
  
  try {
    isSubmitting.value = true
    await userApi.addUser(formModel.value)
    ElMessage.success('用户添加成功')
    visibleDrawer.value = false
    getDataListWithCondition()
  } catch (error) {
    ElMessage.error('添加失败')
  } finally {
    isSubmitting.value = false
  }
}

const clearForm = () => {
  formModel.value = {
    username: '',
    password: '',
    email: '',
    roleIds: []
  }
}

const showAddDrawer = () => {
  clearForm()
  title.value = '添加用户'
  visibleDrawer.value = true
}

const deleteUser = (id: number) => {
  ElMessageBox.confirm('确定要删除该用户吗？此操作不可撤销！', '删除确认', {
    confirmButtonText: '确认删除',
    cancelButtonText: '取消',
    type: 'warning',
    confirmButtonClass: 'el-button--danger',
    center: true
  }).then(async () => {
    try {
      await userApi.deleteUser(id)
      ElMessage.success('用户删除成功')
      getDataListWithCondition()
    } catch (error) {
      ElMessage.error('删除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消删除')
  })
}

const search = () => {
  pageNum.value = 1
  getDataListWithCondition()
}

const resetSearch = () => {
  searchMessage.value = {
    username: '',
    roleName: ''
  }
  pageNum.value = 1
  getDataListWithCondition()
}

const onSizeChange = (size: number) => {
  pageSize.value = size
  getDataListWithCondition()
}

const onCurrentChange = (num: number) => {
  pageNum.value = num
  getDataListWithCondition()
}
</script>

<template>
  <el-card class="card-box">
    <div class="header">
      <h2>用户管理系统</h2>
      <el-button 
        type="primary" 
        @click="showAddDrawer" 
        :icon="Plus"
        class="add-button"
      >
        添加用户
      </el-button>
    </div>

    <el-form inline class="filter-bar">
      <el-form-item label="用户名:" class="filter-item">
        <el-input
          v-model="searchMessage.username"
          placeholder="输入用户名"
          clearable
        />
      </el-form-item>
      
      <el-form-item label="角色:" class="filter-item">
        <el-select
          v-model="searchMessage.roleName"
          placeholder="选择角色"
          clearable
        >
          <el-option
            v-for="role in roleOptions"
            :key="role.id"
            :label="role.name"
            :value="role.name"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item class="filter-item action-buttons">
        <el-button type="primary" @click="search">搜索</el-button>
        <el-button @click="resetSearch">重置</el-button>
      </el-form-item>
    </el-form>

    <div class="responsive-table-container">
      <table class="custom-table">
        <thead>
          <tr>
            <th>编号</th>
            <th>用户名</th>
            <th>邮箱</th>
            <th>角色</th>
            <th>创建时间</th>
            <th>操作</th>
          </tr>
        </thead>
        <tbody>
          <tr v-for="item in userList" :key="item.id">
            <td>{{ item.id }}</td>
            <td>{{ item.username }}</td>
            <td>{{ item.email }}</td>
            <td>
              <div class="role-tags">
                <el-tag
                  v-for="role in item.roles"
                  :key="role"
                  type="info"
                  class="role-tag"
                >
                  {{ role }}
                </el-tag>
              </div>
            </td>
            <td>{{ item.createdAt }}</td>
            <td>
              <div class="action-btns">
                <el-button
                  :icon="Delete"
                  circle
                  plain
                  size="small"
                  type="danger"
                  @click="deleteUser(item.id)"
                />
              </div>
            </td>
          </tr>
          <tr v-if="userList.length === 0">
            <td colspan="6" class="text-center py-4">
              <el-empty description="暂无用户数据" />
            </td>
          </tr>
        </tbody>
      </table>
    </div>

    <div class="pagination-container">
      <el-pagination
        v-model:current-page="pageNum"
        v-model:page-size="pageSize"
        :page-sizes="[5, 7, 10, 20]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
        @size-change="onSizeChange"
        @current-change="onCurrentChange"
      />
    </div>

    <el-dialog
      v-model="visibleDrawer"
      :title="title"
      width="50%"
      :close-on-click-modal="false"
    >
      <el-form 
        :model="formModel" 
        label-width="100px" 
        class="drawer-form"
      >
        <el-form-item label="用户名" prop="username" required>
          <el-input
            v-model="formModel.username"
            placeholder="请输入用户名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="密码" prop="password" required>
          <el-input
            v-model="formModel.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email" required>
          <el-input
            v-model="formModel.email"
            placeholder="请输入邮箱"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="角色" prop="roleIds" required>
          <el-select
            v-model="formModel.roleIds"
            multiple
            placeholder="请选择角色"
            class="role-select"
          >
            <el-option
              v-for="role in roleOptions"
              :key="role.id"
              :label="role.name"
              :value="role.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item class="form-actions">
          <el-button
            type="primary"
            @click="handleSubmit"
            :loading="isSubmitting"
            class="submit-btn"
          >
            提交
          </el-button>
          <el-button @click="visibleDrawer = false">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </el-card>
</template>

<style lang="scss" scoped>
.card-box {
  width: 100%;
  max-width: 100%;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.08);
  display: flex;
  flex-direction: column;
  padding: 0;
  overflow: hidden;
}

.header {
  padding: 0.8rem 1.2rem;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-bottom: 1px solid #e6eaf0;
  background-color: #f7f9fc;
  
  h2 {
    font-weight: 600;
    font-size: 1.4rem;
    color: #333;
    user-select: none;
    margin: 0;
  }

  .add-button {
    font-weight: 500;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  }
}

.filter-bar {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
  padding: 12px;
  align-items: center;
  background-color: #f7f9fc;
}

.filter-item {
  margin-bottom: 0 !important;
  flex: 1;
  min-width: 200px;
}

.action-buttons {
  flex: none;
  margin-left: auto;
}

.responsive-table-container {
  overflow-x: auto;
  padding: 0.8rem;
}

.custom-table {
  width: 100%;
  border-collapse: separate;
  border-spacing: 0 6px;
  font-size: 0.9rem;

  thead tr {
    background-color: #f5f7fa;
    color: #606266;
    font-weight: 600;
  }

  th, td {
    padding: 8px 12px;
    text-align: left;
    vertical-align: middle;
    white-space: nowrap;
  }

  tbody tr {
    background-color: #fff;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
    transition: background-color 0.2s ease;

    &:hover {
      background-color: #f4f9ff;
    }
  }

  .role-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 6px;
  }

  .role-tag {
    margin-right: 6px;
    margin-bottom: 6px;
    font-size: 13px;
  }

  .action-btns {
    display: flex;
    gap: 0.4rem;

    .el-button {
      padding: 0;
      width: 28px;
      height: 28px;
      display: flex;
      justify-content: center;
      align-items: center;
      border-radius: 50%;
    }
  }
}

.pagination-container {
  padding: 0.8rem;
  display: flex;
  justify-content: center;
}

.text-center {
  text-align: center;
}

.py-4 {
  padding-top: 1rem;
  padding-bottom: 1rem;
}

.drawer-form {
  padding: 1rem;

  .el-form-item {
    margin-bottom: 1rem;

    label {
      font-weight: 500;
      color: #606266;
    }
  }

  .role-select {
    width: 100%;
  }

  .form-actions {
    margin-top: 2rem;
    display: flex;
    justify-content: flex-end;
    gap: 1rem;

    .submit-btn {
      min-width: 100px;
    }
  }
}

@media (max-width: 768px) {
  .filter-item {
    min-width: 100%;
  }
  
  .action-buttons {
    margin-left: 0;
    width: 100%;
    display: flex;
    justify-content: flex-end;
    gap: 8px;
  }

  .header {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;

    .add-button {
      width: 100%;
    }
  }
}
</style>